// stores/websocket.ts
import { defineStore } from 'pinia'
import Cookies from 'js-cookie'
import axios from 'axios'
import { reactive, ref } from 'vue'
interface messageL {
  content: string
  createTime: string
  id: number
  sessionId: number
  speaker: speaker
}
interface speaker {
  avatarUrl: string
  id: number
  isAdmin: string
  nickname: string
}
interface lastMessage {
  content: string
  createTime: string
  id: number
  speaker: speaker
}
interface session {
  avatarUrl: string
  id: number
  lastMessage: lastMessage
  messageIdList: number[]
  name: string
  numMember: number
  uncheckNum: number
}
interface MessageDTO {
  speakerId: number
  nickname: string
  avatarUrl: string
  sessionId: number
  content: string
}
export const useWebSocketStore = defineStore('websocket', () => {
  let sessionId = ref<number>(0)
  let show = ref([true, false, false])//Chat.vue里聊天，关注，粉丝三组件显示隐藏
  let userId = sessionStorage.getItem('userId')//登录用户id
  let unreadCountMap = reactive<Record<number, number>>({})//对应sessionId对应未读消息数
  let checkDelId = reactive<Record<number, boolean>>({})//对应消息id,对应是否删除
  let unCheckNum = ref<number>(0)//总未读消息
  let socket: any//websocke
  let isConnected = ref<boolean>(false)//webSocket是否链接
  let message: MessageDTO[] = reactive([])//
  let sessionList: session[] = reactive([])//会话列表
  let wsMessageList: messageL[] = reactive([])//聊天消息列表
  let MessageList = reactive<Record<number, messageL[]>>({})
  let lastMessage: messageL = reactive({//最新发送来的数据
    content: '',
    createTime: '',
    id: 0,
    sessionId: 0,
    speaker: {
      avatarUrl: '',
      id: 0,
      isAdmin: '',
      nickname: ''
    }
  })
  let wsLastMessage = reactive<Record<number, messageL>>({})
  // 连接webSocket
  function connect(url: string) {
    socket = new WebSocket(url)

    //连接成功设置已连接
    socket.onopen = () => {
      // alert('连接成功')
      isConnected.value = true
    }

    // 发送消息，接收消息都会触发
    socket.onmessage = async (event: any) => {
      console.log('更新前的消息列表' + JSON.stringify(wsMessageList));

      const newMessage = JSON.parse(event.data)
      console.log(newMessage.sessionId);

      // 确保wsLastMessage[newMessage.sessionId]存在
      if (!wsLastMessage[newMessage.sessionId]) {
        wsLastMessage[newMessage.sessionId] = { ...newMessage }
      } else {
        // 更新最后一条消息
        Object.assign(wsLastMessage[newMessage.sessionId], newMessage)
      }

      console.log('获取到的sessioniD'+sessionId.value);
      
      if (sessionId.value == newMessage.sessionId) {
        console.log('进去了');
        
        await axios({
          url: '/api/message/setUncheckNumZero',
          method: 'post',
          params: {
            sessionId: sessionId.value
          }
        })
      }
      // 如果是用户自己发的消息总未读消息数不会++
      if (newMessage.speaker.id != Number(userId)&&sessionId.value != newMessage.sessionId) {
        unCheckNum.value++
        console.log(newMessage.speaker.id + ':' + Number(userId));
        // 正确更新未读计数：如果不存在则初始化为1，存在则+1
        if (unreadCountMap[newMessage.sessionId] === undefined) {
          unreadCountMap[newMessage.sessionId] = 1
        } else {
          unreadCountMap[newMessage.sessionId]++
        }
      }

      // 最新消息为否删除勾选
      if (wsLastMessage[newMessage.sessionId]) {
        checkDelId[wsLastMessage[newMessage.sessionId].id] = false
      }

      // 将新消息添加到消息列表（创建新对象避免引用问题）
      // wsMessageList.push({ ...newMessage })
      // 确保MessageList[newMessage.sessionId]存在
      if (!MessageList[newMessage.sessionId]) {
        MessageList[newMessage.sessionId] = []
      }
      if (wsLastMessage[newMessage.sessionId]) {
        MessageList[newMessage.sessionId].push({ ...wsLastMessage[newMessage.sessionId] })
      }
      console.log('最新的消息列表' + JSON.stringify(wsMessageList));
      // console.log('获取到的最新消息' + JSON.stringify(lastMessage));


      const sessionListAxios = await axios({
        url: '/api/session/getSessionList',
      })
      // 清空并重新设置会话列表，确保响应式更新
      sessionList.length = 0
      sessionListAxios.data.data.forEach((session: any) => {
        sessionList.push({ ...session })
      })
    }

    socket.onclose = (error: any) => {
      Cookies.remove('checkLian')
      // alert(error)
      isConnected.value = false
    }
  }
  // 断开webSocket
  function disconnect() {

    Cookies.remove('checkLian')

    if (socket) {
      console.log('你有断开吗');
      socket.close()
      socket = null
      isConnected.value = false
    }
  }

  // 发送信息
  function sendMessage(message: MessageDTO) {
    console.log('发送消息' + message);
    if (socket && isConnected) {
      socket.send(JSON.stringify(message))
    }
  }


  // 清空checkDelId对象（完全清空）
  function clearCheckDelId() {
    // 正确清空reactive对象的方法：删除所有属性
    Object.keys(checkDelId).forEach(key => {
      delete checkDelId[Number(key)]
    })
  }


  return {
    sessionId,
    wsLastMessage,
    MessageList,
    show,
    checkDelId,
    unreadCountMap,
    unCheckNum,
    wsMessageList,
    lastMessage,
    message,
    isConnected,
    sessionList,
    connect,
    disconnect,
    sendMessage,
    clearCheckDelId,
  }
})
